import time
import os
import pickle

def format_output(analysis_output,result_file):#=analysis_output,which is a dictionary
    #analysis_output is all data to be used:

#    analysis_output["start_time"] = start_time
#    analysis_output["time_sec"] = time_sec
#    analysis_output["proj_name"] = proj_name
#    analysis_output["num_snps"] = num_genotypes_before_filter
#    analysis_output["valid_snps"] = valid_pkl   
#    analysis_output["num_valid_snps"] = len(filtered_genotype_names)
#    analysis_output["monomorph_snps"] = monomorph_pkl    
#    analysis_output["num_monomorph_snps"] = len(monomorph_genotypes)
#    analysis_output["significance_level"] = significance_level
#    analysis_output["num_subjects"] = genotype_matrix.shape[1] 
#    analysis_output["class"] = job["class"][0]
#    analysis_output["class_type"] = class_type_select #change to import file    
#    analysis_output["perform_bonf"] = perform_bonferoni_correction#boolean  
#    analysis_output["bonferroni_correction"] = bonf_correct 
#    analysis_output["phenotype_file"] = phenotype_file #change to import file
#    analysis_output["genotype_file"] = genotype_file #change to import file
#    analysis_output["minimumAllFre"] = minallfr
#    analysis_output["epistasis_data"] = epistasis_data

#  analysis_output["epistasis_data"] is a list of trait_results, which are saved as a dictionary containing:
     #trait_result["trait_name"] = name_trait
     #trait_result["snp_interactions"] = []
     #trait_result["AllGenFreq"] = []
     #trait_result["Entropy"] = []
     #trait_result["trait_mean"] = trait_mean
     #trait_result["trait_variance"] = trait_var
     #trait_result["relative_significant"] = relative_sign 
     #trait_result["epistasis_significant"] = epistasis_significant  
        
        # trait["snp_interactions"] contains job_value_temp["snp1"],job_value_temp["snp2"], allel_val[2], epi_calc, entropy_data, and entropy_data_weight; (five entries)
        
        # trait_result["Entropy"] should contain the three entropy calculations
 
    #Create class-specific folders
    output_folder = "epifiles"+ analysis_output["class"]
    if os.path.exists(output_folder):
        os.chdir(output_folder)
    else: 
        os.mkdir(output_folder)
        os.chdir(output_folder)

    summary_file = "summary_class_%s.txt" % str(analysis_output["class"])
    analysis_summary(analysis_output, summary_file)
    
    files_open = []
    for trait in analysis_output["epistasis_data"]:       
        selected_class= analysis_output["class"]#directly from dictionary, incorp below
        #Generates output files
        files_open = snp_interaction_summary_open(trait["trait_name"],selected_class)
         
        entropy_results = trait["Entropy"]
        entlengt = len(entropy_results)#NBfjerne overalt
 
        entropy_results_weight = trait["Entropy_weight"]# a list forkert call til bergeninger        
        entlengtw = len(entropy_results_weight)
 
        trait_summary(trait, summary_file,entropy_results,entropy_results_weight,entlengt,selected_class)#summary_file = output_file, corrected
        
        for interaction in trait["snp_interactions"]:#call in analysis_output["epistasis_data"] 
            snp_interaction_summary_out(files_open, allel_val=interaction[2], epi_calc=interaction[3],entrop = interaction[4],entropw = interaction[5], selected_class=analysis_output["class"])##??selected class??
            ##epicalc contains gteffects, gtvariance, gtvariance_sumLD,gtvariance_sumNLD
            
            
    for fd in files_open:
        fd.close()
    elapsed_time = time.time() - analysis_output["time_sec"]
    elaps_time = "{0} {1}".format("Elapsed time in seconds", str(elapsed_time))
    print elaps_time

    f = open(summary_file, "a")
    summary_outputE = 'End of calculations'+' '+str(time.asctime())+'\n\n'
    f.writelines(summary_outputE)
    f.writelines(elaps_time)
    
    f.close()
    
    os.chdir("..") # changing back to original folder
    
    
def analysis_summary(analysis_dict, summary_file):
    """Summary file"""

    summary_lines = []
    proj_name = analysis_dict["proj_name"]#unik project run for the Project
#    proj_name = analysis_dict["proj_name"]
    li_summary_mono_snps = analysis_dict["monomorph_snps"]
    num_monomorph_snps = analysis_dict["num_monomorph_snps"]
    li_summary_valid_snps = analysis_dict["valid_snps"]    
    num_valid_snps = analysis_dict["num_valid_snps"]
    num_snps = analysis_dict["num_snps"]
    num_interactions = num_valid_snps*(num_valid_snps-1)/2
    significance_level = analysis_dict["significance_level"]
    bonf_perform = analysis_dict["perform_bonf"]
    Bonf_correct = analysis_dict["bonferroni_correction"]
    num_subjects = analysis_dict["num_subjects"]
    class_select = analysis_dict["class"]
    phenotype_file =  analysis_dict["phenotype_file"]
    genotype_file =  analysis_dict["genotype_file"]
    class_type =  analysis_dict["class_type"]
    start_time = analysis_dict["start_time"]
    maf = analysis_dict["minimumAllFre"]


    summary_output1 = 'Start of calculations'+' '+str(start_time)+'\n\n'
    summary_lines.append(summary_output1)    

    summary_outputA = 'Project ID:   ' + str(proj_name) +'\n\n'
    summary_lines.append(summary_outputA) 
    
    summary_outputF = "Files used in epistasis calculations:" +"\n\n"
    summary_lines.append(summary_outputF)     

    summary_outputP = "Phenotype file            "+ str(phenotype_file) +"\n"
    summary_lines.append(summary_outputP) 

    summary_outputG = "Genotype file             "+ str(genotype_file) +"\n"
    summary_lines.append(summary_outputG) 

    summary_outputC = "Partition file            "+ str(class_type) +"\n"
    summary_lines.append(summary_outputC) 

    summary_outputPcut = "Partition cut          "+ "To be implemented" +"\n"
    summary_lines.append(summary_outputPcut) 

    summary_outputS = "Minimum allele frequence  "+ str(maf) +"\n\n"
    summary_lines.append(summary_outputS) 
    
    summary_output0 = "Summary of entire currated data file"+"\n\n"
    summary_lines.append(summary_output0) 

    summary_output10 = "Class                     "+ str(class_select) +"\n\n"
    summary_lines.append(summary_output10) 

    summary_output13 = "Number of subjects        "+ str(num_subjects) +"\n\n"
    summary_lines.append(summary_output13) 

    summary_output4 = "Total number of SNPs       "+ str(num_snps) +"\n"
    summary_lines.append(summary_output4) 

    summary_output5 = "Number of monomorph SNPs   "+ str(num_monomorph_snps) +"\n"
    summary_lines.append(summary_output5) 

    summary_output6 = "Number of polymorphic SNPs "+ str(num_valid_snps) +"\n\n"
    summary_lines.append(summary_output6) 

    summary_output16 = "Maximum number of possible interactions (valid SNPs only) "+ str(num_interactions) +"\n\n"
    summary_lines.append(summary_output16) 

    summary_output14 = "Nominal signficance level "+ str(significance_level) +"\n"
    summary_lines.append(summary_output14) 

    if bonf_perform == True:
       summary_output15 = "Bonferoni corrected       "+ str(Bonf_correct) +"\n\n"
       summary_lines.append(summary_output15)     
    else:
       summary_output15a = "No correction for multiple testing (Bonferoni)c" +"\n\n"
       summary_lines.append(summary_output15a)

    f = open(summary_file, "w")
    f.writelines(summary_lines)
    f.close()

    #Valid SNPs
    validsnps_file = "Valid snps"
    validsnpstemp_file = "Valid snps temp" #delete when called from  X.epi_res_pkl
    summary_valid = []
    valid_sum0 = 'Start of calculations'+' '+str(start_time)+'\n\n'
    summary_valid.append(valid_sum0)     
    
    valid_sum2 = "Valid SNPs in selected class" +"\n\n"
    summary_valid.append(valid_sum2)     

    valid_sum1 = 'Project ID:    ' + str(proj_name) +'\n\n'
    summary_valid.append(valid_sum1) 
    
    valid_sum3 = "Genotype file: "+ str(genotype_file) +"\n\n"
    summary_valid.append(valid_sum3) 

    valid_sum5 = "Class:         "+ str(class_select) +"\n\n"
    summary_valid.append(valid_sum5)     
    
    valid_sum4 = "Number of valid SNPs: "+ str(num_valid_snps) +"\n\n"
    summary_valid.append(valid_sum4) 

    valid_header = 'SNP' + '\t'+ 'Gene' + "\n\n"
    summary_valid.append(valid_header) 

    va = open(validsnps_file, "w")        
    va.writelines(summary_valid)   
    for i in range(0,len(li_summary_valid_snps)):
        val_out = li_summary_valid_snps[i]   
        va.write(val_out)# 

    va.close()

    #Monomorph SNPs
    mono_morph_file = "Monomorph snps"
    summary_mono = []
    mono_sum0 = 'Start of calculations'+' '+str(start_time)+'\n\n'
    summary_mono.append(mono_sum0)     
    
    mono_sum2 = "Monomoph SNPs in selected class" +"\n\n"
    summary_mono.append(mono_sum2)     

    mono_sum1 = 'Project ID:   ' + str(proj_name) +'\n\n'
    summary_mono.append(mono_sum1) 
    
    mono_sum3 = "Genotype file: "+ str(genotype_file) +"\n\n"
    summary_mono.append(mono_sum3) 

    mono_sum5 = "Class:         "+ str(class_select) +"\n\n"
    summary_mono.append(mono_sum5)         

    mono_sum4 = "Number of monomorph SNPs: "+ str(num_monomorph_snps) +"\n\n"
    summary_mono.append(mono_sum4) 

    mono_header = 'SNP' + '\t'+ 'Gene' + "\n\n"      
    summary_mono.append(mono_header) 

    m = open(mono_morph_file, "w")        
    m.writelines(summary_mono)   
           
    for i in range(0,len(li_summary_mono_snps)):
        mo_out = li_summary_mono_snps[i]   
        m.write(mo_out)# 

    m.close()
    
def trait_summary(trait_analysis_output, summary_file,entropy_results,entropy_results_weight,entlengt,selected_class):
  
    trait_mean = trait_analysis_output["trait_mean"]
    trait_variance = trait_analysis_output["trait_variance"]  
    trait_name = trait_analysis_output["trait_name"] 
    class_select = selected_class

    epistasis_significant = trait_analysis_output["epistasis_significant"] 
    relative_significant = trait_analysis_output["relative_significant"]        
     
    summary_lines = []

    summary_output3 = "Trait: "+ trait_name +"\n\n"
    summary_lines.append(summary_output3)

    summary_output7 = "  Phenotypic mean            "+ str(trait_mean) +"\n"
    summary_lines.append(summary_output7)
    
    summary_output8 = "  Phenotypic variance        "+ str(trait_variance) +"\n"
    summary_lines.append(summary_output8)

    summary_output17 = "  Significant interactions   "+ str(epistasis_significant)+" ("+ str(relative_significant)+")" +"\n\n"
    summary_lines.append(summary_output17)

    summary_output9 = "  Entropy (Shannon) " +"\n"
    summary_lines.append(summary_output9)

    summary_outputAllS = "    Allele total                   "+ str(entropy_results[0]) +"\n"
    summary_lines.append(summary_outputAllS)

    summary_outputAllSN = "    Allele normalized              "+ str(entropy_results[1]) +"\n"
    summary_lines.append(summary_outputAllSN)

    summary_outputGeneS = "    Genotype real                  "+ str(entropy_results[2]) +"\n"
    summary_lines.append(summary_outputGeneS)

    summary_outputGeneSN = "    Genotype real normalized       "+ str(entropy_results[3]) +"\n"
    summary_lines.append(summary_outputGeneSN)

    summary_outputGeneES = "    Genotype expected              "+ str(entropy_results[4]) +"\n"
    summary_lines.append(summary_outputGeneES)

    summary_outputGeneESN = "    Genotype expected normalized   "+ str(entropy_results[5]) +"\n\n"
    summary_lines.append(summary_outputGeneESN)

#Weighted allel output Shannon
    summary_outputW1 = "  Entropy (Shannon) weighted " +"\n"
    summary_lines.append(summary_outputW1)

    summary_outputAllW2 = "    Allele total                   "+ str(entropy_results_weight[0]) +"\n"
    summary_lines.append(summary_outputAllW2)

    summary_outputAllW3 = "    Allele normalized              "+ str(entropy_results_weight[1]) +"\n"
    summary_lines.append(summary_outputAllW3)

    summary_outputAllW2 = "    Allele total (abs)              "+ str(entropy_results_weight[2]) +"\n"
    summary_lines.append(summary_outputAllW2)

    summary_outputAllW3 = "    Allele normalized (abs)         "+ str(entropy_results_weight[3]) +"\n\n"
    summary_lines.append(summary_outputAllW3)

    f = open(summary_file, "a")
    f.writelines(summary_lines)
    f.close()


def snp_interaction_summary_open(name_trait, selected_class):

	#Create files for basic data (allelfrequences, effects, and variances (LD and NLD)
    #Allel frequence file
    genotype_allefr = open("GenotypeAllelfr "+name_trait+" Class "+selected_class, "w")
    genotype_allefr_header = 'SNP1' +' '+ 'Gene'+' '+'AA'+ ' ' + 'Aa'+ ' '+ 'aa' + ' ' + "Allel_A" + ' ' 'Allel_a'\
                          +' '+'SNP2' + ' '+'Gene'+' '+'BB'+ ' ' + 'Bb'+ ' '+ 'bb' + ' ' + "Allel_B" + ' ' 'Allel_b'+ "\n"
    genotype_allefr.write(genotype_allefr_header)
        
    #Effect file
    genotype_effects = open("GenotypeEffects "+name_trait+" Class "+selected_class, "w")
    genotype_effects_header = 'SNP1' +' ' + 'Gene'+' ' +'Add_A'+ ' ' + 'Add_a'+ ' '+ 'DomAA'\
      + ' ' +'DomAa' + ' ' + 'Domaa' + ' ' 'SNP2' + ' ' + 'Gene'+' '+ "Add_B" + ' ' 'Add_b'\
      +' '+'DomBB' +' '+'DomBb'+ ' ' + 'Dombb'+' '+' ' \
      + 'AddAdd_AB'+' '+'AddAdd_Ab'+' '+'AddAdd_aB'+' '+'AddAdd_ab'+ ' '\
      +'AddDom_AxBB'+' '+'AddDom_AxBb' + ' ' + 'AddDom_Axbb' + ' '\
      +'AddDom_axBB'+' '+'AddDom_axBb'+' '+'AddDom_axbb'+' '\
      +'AddDom_AABx'+' '+'AddDom_AaBx' + ' ' + 'AddDom_aaBx' + ' '\
      +'AddDom_AAbx'+' '+'AddDom_Aabx'+' '+'AddDom_aabx'+ ' '\
      +'DomDomAABB'+' '+'DomDomAABb'+' '+'DomDomAAbb'+' '+'DomDomAaBB'+' '+'DomDomAaBa'+' '\
      +'DomDomAabb'+' '+'DomDomaaBB'+' '+'DomDomaaBb'+' '+'DomDomaabb'+"\n"
    genotype_effects.write(genotype_effects_header)    

    #Variance detail file
    genotype_variance = open("GenotypeVariance "+name_trait+" Class "+selected_class, "w")
    genotype_variance_header = 'SNP1' +' '+ 'Gene'+' '+'AddVarAa'+ ' ' + 'DomVarAA'+ ' '+ 'DomVarAa'\
      + ' ' +'DomVaraa' + ' ' + 'SNP2' + ' '+ 'Gene'+' ' + "AddVarBb" + ' ' 'DomVarBB'\
      +' '+'DomVarBb' +' '+'DomVarbb'+' '+'AddAddVarAB'+' ' \
      + 'AddAddVarAb'+' '+'AddAddVaraB'+' '+'AddAddVarab'+ ' '\
      +'AddDomVar_AxBB'+' '+'AddDomVar_AxBb' + ' ' + 'AddDomVar_Axbb' + ' '\
      +'AddDomVar_axBB'+' '+'AddDomVar_axBb'+' '+'AddDomVar_axbb'+' '\
      +'AddDomVar_AABx'+' '+'AddDomVar_AaBx' + ' ' + 'AddDomVar_aaBx' + ' '\
      +'AddDomVar_AAbx'+' '+'AddDomVar_Aabx'+' '+'AddDomVar_aabx'+ ' '\
      +'DomDomVarAABB'+' '+'DomDomVarAABb'+' '+'DomDomVarAAbb'+' '+'DomDomVarAaBB'+' '\
      +'DomDomVarAaBa'+' '+'DomDomVarAabb'+' '+'DomDomVaraaBB'+' '+'DomDomVaraaBb'+' '\
      +'DomDomaabb'+"\n"
    genotype_variance.write(genotype_variance_header)    
        
    #Variance summary file
    genotype_variance_sumLD = open("GenotypeVarSum LD "+name_trait+" Class "+selected_class, "w")
    genotype_variance_header_sum = 'SNP1' +' '+ 'Gene'+' '+'SNP2'+ ' '+ 'Gene'+' ' + 'PhenoVar'+ ' '\
        +'GenoVar'+' '+'Additive'+' '+'Dominant'+' '+'AddAdd'+' '+'AddDom(A)'+' '\
        +'AddDom(B)'+' '+'DomDom'+' '+'EpiVar'+' '+' '+'Geno/Pheno'\
        +' '+'Epi/Pheno'+' '+'Epi/Geno'+' '+'Check'+' '+'F-stat'\
        + ' '+ 'dfdenom'+' '+'p-values'+"\n"      
    genotype_variance_sumLD.write(genotype_variance_header_sum) 

    #Variance summary file non LD outputs
    genotype_variance_sumNLD = open("GenotypeVarSum NLD "+name_trait+" Class "+selected_class, "w")
    genotype_variance_header_sum = 'SNP1' +' '+ 'Gene'+' '+'SNP2'+ ' '+ 'Gene'+' ' + 'PhenoVar'+ ' '\
        +'GenoVar'+' '+'Additive'+' '+'Dominant'+' '+'AddAdd'+' '+'AddDom(A)'+' '\
        +'AddDom(B)'+' '+'DomDom'+' '+'EpiVar'+' '+' '+'Geno/Pheno'\
        +' '+'Epi/Pheno'+' '+'Epi/Geno'+' '+'Check'+' '+'F-stat'\
        + ' '+ 'dfdenom'+' '+'p-values'+"\n"      
    genotype_variance_sumNLD.write(genotype_variance_header_sum) 

	###Create files for calculating based on basic data
    #Entropy summary file allele
    entropy_allel = open("Entropy allel "+name_trait+" Class "+selected_class, "w")
    entropy_allel_header = 'SNP1' +' '+ 'Gene'+' '+'EntA1'+ ' '+ 'EntA2'+' ' + 'EntAsum'+ ' '\
        +'SNP2'+' '+'Gene'+' '+'EntB1'+' '+'EntB2'+' '+'EntBsum'+' '\
        +'EntEpiSum'+"\n"      
    entropy_allel.write(entropy_allel_header) 

    #Entropy summary file genotypes real
    entropy_geno = open("Entropy genotype real "+name_trait+" Class "+selected_class, "w")
    entropy_geno_header = 'SNP1' +' '+ 'Gene'+' '+'GenoA1'+ ' '+ 'GenoA2'+' ' + 'GenoA3' + ' '+ 'GenoAsum'+ ' '\
        +'SNP2'+' '+'Gene'+' '+'GenoB1'+' '+'GenoB2'+' '+'GenoB3' + ' '+ 'GenoBsum'+' '\
        +'GenoEpiSum'+"\n"      
    entropy_geno.write(entropy_geno_header) 

    #Entropy summary file genotypes expected
    entropy_geno_exp = open("Entropy genotype expected "+name_trait+" Class "+selected_class, "w")
    entropy_geno_header_exp = 'SNP1' +' '+ 'Gene'+' '+'eGenoA1'+ ' '+ 'eGenoA2'+' ' + 'eGenoA3' + ' '+ 'eGenoAsum'+ ' '\
        +'SNP2'+' '+'Gene'+' '+'eGenoB1'+' '+'eGenoB2'+' '+'eGenoB3' + ' '+ 'eGenoBsum'+' '\
        +'eGenoEpiSum'+"\n"      
    entropy_geno_exp.write(entropy_geno_header_exp) 

    #Entropy summary file allele
    entropy_allel_weight = open("Entropy allel weighted "+name_trait+" Class "+selected_class, "w")
    entropy_allel_header = 'SNP1' +' '+ 'Gene'+' '+'EntA1'+ ' '+ 'EntA2'+' ' + 'EntAsum'+ ' '\
        +'SNP2'+' '+'Gene'+' '+'EntB1'+' '+'EntB2'+' '+'EntBsum'+' '\
        +'EntEpiSum'+"\n"      
    entropy_allel_weight.write(entropy_allel_header) 

    entropy_allel_weight_abs = open("Entropy allel weighted abs "+name_trait+" Class "+selected_class, "w")
    entropy_allel_weight_abs.write(entropy_allel_header) 
    
    return genotype_allefr,genotype_effects,genotype_variance,genotype_variance_sumLD,genotype_variance_sumNLD,entropy_allel,entropy_geno,entropy_geno_exp,entropy_allel_weight,entropy_allel_weight_abs
    
def snp_interaction_summary_out(files_open, allel_val, epi_calc, entrop, entropw,selected_class):
    
    """Output"""
    files_open[0].write(allel_val)
    files_open[1].write(epi_calc[0])#effect size
    files_open[2].write(epi_calc[1])#variance (all)
    files_open[3].write(epi_calc[2])#variance sum LD
    files_open[4].write(epi_calc[3])#variance sum NLD   

    #Entropy output; NB entrop is a list with thre files
    files_open[5].write(entrop[0])#Entropy allel   
    files_open[6].write(entrop[1])#Entropy genotype real    
    files_open[7].write(entrop[2])#Entropy genotype expected   
    files_open[8].write(entropw[0])#Entropy allel weighted effect  
    files_open[9].write(entropw[1])#Entropy allel weighted effect absolute values
    
        
    
